package org.alicuu.dao;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: Danny
 * Date: 16/07/06
 * Time: 18:23
 */
class DBManager {
    private static Configuration conf;
    private static DBConnectionPool pool;

    static {
        Properties properties = new Properties();
        try {
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        conf.setDriver(properties.getProperty("driver"));
        conf.setUser(properties.getProperty("user"));
        conf.setPassword(properties.getProperty("password"));
        conf.setUrl(properties.getProperty("url"));
        conf.setdBVendor(properties.getProperty("vendor"));
        conf.setSrcPath(properties.getProperty("srcPath"));
        conf.setPersistentObjPackage("persistentObjPackage");
        conf.setPoolMaxSize(Integer.valueOf(properties.getProperty("maxPoolSize")));
        conf.setPoolMinSize(Integer.valueOf(properties.getProperty("minPoolSize")));
    }

    static Configuration getConf() {
        return conf;
    }

    static Connection createConnection() {
        try {
            Class.forName(conf.getDriver());
            return DriverManager.getConnection(conf.getUrl(), conf.getUser(), conf.getPassword());
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    static Connection getConnection() {
        if (pool == null)
            pool = new DBConnectionPool();
        return pool.getConnection();
    }

    static void close(ResultSet rs, Statement stat, Connection conn) {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (stat != null)
                stat.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        pool.close(conn);
    }


}
